#include"SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);
	ps->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->capicity = 4;
	ps->size = 0;
}

void SLDestroy(SL* ps) 
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capicity = 0;
	ps->size = 0;
}
void SLCheckCapicity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capicity)
	{
		SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capicity * 2);
		if (tmp == NULL)
		{
			perror("realloc fail\n");
			return;
		}
		ps->a = tmp;
		ps->capicity *= 2;
	}
}

void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapicity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	SLCheckCapicity(ps);
	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

void SLPopback(SL* ps)
{
	assert(ps);
	ps->size--;
}

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	int start = 0;
	while (start < ps->size)
	{
		ps->a[start] = ps->a[start + 1];
		start++;
	}
	ps->size--;
}

void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapicity(ps);
	int end = ps->size-1;
	while (end >= pos)
	{
		ps->a[end+1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}

//void SLErase(SL* ps, int pos)
//{
//	assert(ps);
//	assert(pos >= 0 && pos < ps->size);
//	while (pos < ps->size)
//	{
//		ps->a[pos] = ps->a[pos+1];
//		pos++;
//	}
//	ps->size--;
//}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	int start = pos + 1;
	while (start < ps->size)
	{
		ps->a[start - 1] = ps->a[start];
		start++;
	}
	ps->size--;
}

int SLFind(SL* ps,SLDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLModify(SL* ps, int pos, SLDataType x)
{
	assert(pos >= 0 && pos < ps->size);
	ps->a[pos] = x;
}